<template>
  <basic-container v-loading="loading" element-loading-text="数据加载中...">
    <dataList
      ref="dictCrud"
      hideFilterBtn
      openIndex
      operaColumnWidth="130"
      :pageInfo="pager"
      :listData="tableData"
      :dataInfo="dataInfo"
      :operaInfo="operaInfo"
      :menuList="menuList"
      :listLayout="['menu','filter']"
      :filterList="filterList"
      @btn-click="handleBtnClick"
      @menu-click="handleMenuClick"
    ></dataList>
    <v-dialog :title="isEdit ? '编辑' : '新增'" :show.sync="dialogVisible" width="1000px" v-loading="dialogLoading" @beforeClose="beforeClose" element-loading-text="正在保存..." v-if="dialogVisible">
      <el-form ref="dictForm" :model="tableOption" label-width="80px" :rules="tableOption_rules">
        <el-form-item label="类型" prop="type">
          <el-input v-halfCharCode v-model="tableOption.type" placeholder="请输入模板名称" :disabled="isEdit" />
        </el-form-item>
        <el-form-item label="描述" prop="description">
          <el-input v-halfCharCode v-model="tableOption.description" placeholder="请输入模板编码" />
        </el-form-item>
        <el-form-item label="字典类型" prop="system">
          <el-select clearable placeholder="请选择字典类型" v-model="tableOption.system">
            <el-option v-for="item in dictTypes" :key="item.value" :label="item.label" :value="item.value"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="备注信息" prop="remarks">
          <el-input v-halfCharCode type="textarea" maxlength="100" placeholder="请输入备注信息" v-model="tableOption.remarks" />
        </el-form-item>
        <el-form-item label="创建时间" prop="createTime" v-if="isEdit">
          <el-input v-halfCharCode v-model="tableOption.createTime" placeholder="请输入创建时间" disabled />
        </el-form-item>
      </el-form>
      <span slot="foot">
        <el-button v-throttle="[commit]">{{isEdit ? '修 改' : '保 存'}}</el-button>
        <el-button @click="handleCancel">取 消</el-button>
      </span>
    </v-dialog>
    <dictInner ref="dictInner"></dictInner>
  </basic-container>
</template>

<script>
import { addObj, delObj, fetchList, putObj } from '~/admin/api/dict'
import dictInner from './dict-inner'
export default {
  name: "dict",
  components: { dictInner },
  provide () {
    return {
      initList: this.getListData
    };
  },
  beforeMount () {
    this.getListData()
    this.dictTypes = this.getDict('dict_type')
  },
  data () {
    return {
      tableData: [],
      // 请求参数
      params: {
        current: 1,
        size: 10
      },
      // 分页
      pager: {
        total: 0, // 总页数
        current: 1, // 当前页数
        size: 10 // 每页显示多少条
      },
      filterList: [
        { label: '类型', inputType: 'input', name: 'type', placeholder: '请输入类型', defaultValue: '' },
        { label: '描述', inputType: 'input', name: 'description', placeholder: '请输入描述', defaultValue: '' },
        { label: '字典类型', inputType: 'dict', dictName: 'dict_type', name: 'system', placeholder: '请选择字典类型', defaultValue: '' },
      ],
      // 页面loading
      loading: false,
      dictTypes: [],
      // 新增、编辑弹框
      isEdit: false,
      dialogLoading: false,
      dialogVisible: false,
      tableOption: {
        type: '',
        description: '',
        system: '',
        remarks: '',
        createTime: ''
      },
      tableOption_rules: {
        type: [{ required: true, message: '请输入类型', trigger: 'blur' }],
        description: [{ required: true, message: '请输入字典描述', trigger: 'blur' }],
        system: [{ required: true, message: '请输入字典类型', trigger: 'blur' }],
      },
    }
  },
  computed: {
    menuList () {
      return this.getPermissions('sys_dict_add') ? ['add'] : []
    },
    // 权限配置
    permissionList () {
      return {
        editBtn: this.getPermissions('sys_dict_edit'),
        delBtn: this.getPermissions('sys_dict_del'),
        ItemBtn: this.getPermissions('sys_dict_add')
      }
    },
    // 配置表头
    dataInfo () {
      return [
        { label: '类型', prop: 'type', width: '220' },
        { label: '描述', prop: 'description', width: '320', 'show-overflow-tooltip': true },
        { label: '字典类型', prop: 'system', formatter: this.getSystem, width: '150' },
        { label: '备注信息', prop: 'remarks', width: '320', 'show-overflow-tooltip': true },
        { label: '创建时间', prop: 'createTime', width: '220' }
      ]
    },
    // 操作项配置
    operaInfo () {
      return [
        { label: '编辑', name: 'edit', verify: () => this.permissionList.editBtn },
        { label: '删除', name: 'delete', verify: () => this.permissionList.delBtn },
        { label: '字典项', name: 'item', verify: () => this.permissionList.ItemBtn },
      ]
    }
  },
  methods: {
    // 获取列表
    getListData (params = {}) {
      this.loading = true;
      let requestData = { ...this.params, ...params };
      fetchList(requestData)
        .then(res => {
          const { current, size, total, records } = res.data.data;
          this.tableData = records;
          this.params = requestData;
          this.pager = { total, current, size };
        })
        .finally(() => {
          this.loading = false;
        });
    },
    // 菜单点击监听
    handleMenuClick (type) {
      switch (type) {
        case "add":
          this.handleCreate();
          break;
        default:
          this.$message(type);
          break;
      }
    },
    // 按钮点击监听
    handleBtnClick ({ type, row }) {
      switch (type) {
        case 'edit':
          this.handleUpdate(row)
          break;
        case 'delete':
          this.handleDelete(row)
          break;
        case 'item':
          this.handleItem(row)
          break;
        default:
          break;
      }
    },
    // 编辑
    handleUpdate (row) {
      this.tableOption = row
      this.isEdit = true
      this.dialogVisible = true
    },
    // 删除
    handleDelete (row) {
      this.$confirm('是否确认删除数据类型为"' + row.type + '"的数据项?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(function () {
        return delObj(row)
      }).then(() => {
        this.getListData({ current: 1 })
        this.$notify.success('删除成功')
      })
    },
    // 弹框保存
    commit () {
      this.$refs.dictForm.validate(valid => {
        if (valid) {
          this.dialogLoading = true
          if (this.isEdit) {
            putObj(this.tableOption).then(res => {
              if (res.data.code === 0) {
                this.$notify.success('修改成功')
                this.dialogLoading = false
                this.handleCancel()
              } else {
                this.$notify.error('修改失败')
                this.dialogLoading = false
                this.handleCancel()
              }
            }).catch(() => {
              this.dialogLoading = false
            })
          } else {
            addObj(this.tableOption).then(res => {
              if (res.data.code === 0) {
                this.$notify.success('添加成功')
                this.dialogLoading = false
                this.handleCancel()
              } else {
                this.$notify.error('添加失败')
                this.dialogLoading = false
                this.handleCancel()
              }
            }).catch(() => {
              this.dialogLoading = false
            })
          }
        }
      })
    },
    // 弹框取消
    handleCancel () {
      this.tableOption = {}
      this.dialogVisible = false
      this.isEdit = false
      this.getListData()
    },
    beforeClose (done) {
      this.handleCancel()
    },
    // 新增
    handleCreate () {
      this.dialogVisible = true
    },
    // 字典类型初始化
    getSystem (row, column, cellValue) {
      let obj = this.dictTypes.find(p => p.value == cellValue)
      if (obj) {
        return obj.label
      }
      return ''
    },
    //打开字典项
    handleItem: function (row) {
      this.$refs.dictInner.dictInnerShow(row)
    }
  }
}
</script>

<style scoped lang="scss">
.managementDialog {
  /deep/ .el-dialog__body {
    padding: 0;
  }
}
</style>
